package main

import (
	"bytes"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

func startHTTPSServer(config Config, cert tls.Certificate) error {
	// 创建TLS配置
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
	
	// 创建HTTP处理器
	mux := http.NewServeMux()
	
	// /models路由
	mux.HandleFunc("/models", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}
		
		response := map[string]interface{}{
			"object": "list",
			"data": []map[string]interface{}{
				{
					"id":       config.Model,
					"object":   "model",
					"owned_by": "deepseek",
				},
			},
		}
		
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(response)
		fmt.Printf("返回模型列表: %s\n", config.Model)
	})
	
	// /chat/completions路由
	mux.HandleFunc("/chat/completions", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}
		
		handleChatCompletions(w, r, config)
	})
	
	// 默认路由
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello from %s!\n", config.Domain)
		fmt.Fprintf(w, "Target: %s\n", config.Target)
		fmt.Fprintf(w, "Model: %s\n", config.Model)
		fmt.Fprintf(w, "TargetModel: %s\n", config.TargetModel)
	})
	
	// 创建HTTPS服务器
	server := &http.Server{
		Addr:      ":443",
		Handler:   mux,
		TLSConfig: tlsConfig,
	}
	
	fmt.Printf("启动HTTPS服务器在端口443，域名: %s\n", config.Domain)
	return server.ListenAndServeTLS("", "")
}

func handleChatCompletions(w http.ResponseWriter, r *http.Request, config Config) {
	// 读取请求体
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Failed to read request body", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()
	
	// 解析JSON数据
	var data map[string]interface{}
	if err := json.Unmarshal(body, &data); err != nil {
		http.Error(w, "Invalid JSON", http.StatusBadRequest)
		return
	}
	
	// 替换模型ID
	originalModel := ""
	if model, ok := data["model"].(string); ok {
		originalModel = model
		data["model"] = config.TargetModel
		fmt.Printf("模型替换: %s -> %s\n", originalModel, config.TargetModel)
	}
	
	// 重新编码JSON
	modifiedBody, err := json.Marshal(data)
	if err != nil {
		http.Error(w, "Failed to encode JSON", http.StatusInternalServerError)
		return
	}
	
	// 构建目标URL
	targetURL := fmt.Sprintf("%s/v1/chat/completions", config.Target)
	
	// 创建新的请求
	req, err := http.NewRequest("POST", targetURL, bytes.NewReader(modifiedBody))
	if err != nil {
		http.Error(w, "Failed to create request", http.StatusInternalServerError)
		return
	}
	
	// 复制请求头，排除一些可能有问题的头部
	for key, values := range r.Header {
		if key == "Host" || key == "Content-Length" {
			continue
		}
		for _, value := range values {
			req.Header.Add(key, value)
		}
	}
	
	// 设置Content-Type
	req.Header.Set("Content-Type", "application/json")
	
	// 如果配置了API Key，替换Authorization头
	if config.APIKey != "" {
		req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", config.APIKey))
		fmt.Printf("使用配置的API Key替换Authorization头\n")
	}
	
	fmt.Printf("转发请求到: %s\n", targetURL)
	
	// 发送请求
	client := &http.Client{Timeout: 60 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("请求失败: %v\n", err)
		http.Error(w, "Request failed", http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()
	
	// 检查是否是流式响应
	isStream := false
	if streamValue, ok := data["stream"].(bool); ok && streamValue {
		isStream = true
	}
	
	// 复制响应头
	for key, values := range resp.Header {
		if key == "Transfer-Encoding" || key == "Content-Encoding" {
			continue
		}
		for _, value := range values {
			w.Header().Add(key, value)
		}
	}
	
	// 设置状态码
	w.WriteHeader(resp.StatusCode)
	
	if isStream {
		// 流式响应
		fmt.Println("处理流式响应")
		flusher, ok := w.(http.Flusher)
		if !ok {
			http.Error(w, "Streaming not supported", http.StatusInternalServerError)
			return
		}
		
		buffer := make([]byte, 1024)
		for {
			n, err := resp.Body.Read(buffer)
			if n > 0 {
				w.Write(buffer[:n])
				flusher.Flush()
			}
			if err == io.EOF {
				break
			}
			if err != nil {
				fmt.Printf("流式读取错误: %v\n", err)
				break
			}
		}
	} else {
		// 非流式响应
		fmt.Println("处理非流式响应")
		io.Copy(w, resp.Body)
	}
}

func printCertificateInfo(cert tls.Certificate) {
	// 解析证书以获取信息
	if len(cert.Certificate) > 0 {
		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
		if err == nil {
			fmt.Printf("  证书状态: 已加载 (CN=%s)\n", x509Cert.Subject.CommonName)
		} else {
			fmt.Printf("  证书状态: 已加载\n")
		}
	}
}